package org.study.swing.study01.tree;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.Serializable;

/**
 * 作用描述
 * 参考 https://www.cnblogs.com/taoweiji/archive/2013/02/08/2909214.html
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年11月15日
 */
public class TreeDemo2 {
    public static void main(String[] args) {
        testTree1();
    }

    public static void testTree1() {
        JFrame frame = new JFrame("示例：JTree");

        // 创建没有父节点和子节点、但允许有子节点的树节点，并使用指定的用户对象对它进行初始化。
        DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("软件部");
        node1.add(new DefaultMutableTreeNode(new User("小花")));
        node1.add(new DefaultMutableTreeNode(new User("小虎")));
        node1.add(new DefaultMutableTreeNode(new User("小龙")));

        DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("销售部");
        node2.add(new DefaultMutableTreeNode(new User("小叶")));
        node2.add(new DefaultMutableTreeNode(new User("小雯")));
        node2.add(new DefaultMutableTreeNode(new User("小夏")));

        DefaultMutableTreeNode top = new DefaultMutableTreeNode("职员管理");
        top.add(new DefaultMutableTreeNode(new User("总经理")));
        top.add(node1);
        top.add(node2);
        JTree tree = new JTree(top);
        frame.add(tree);

        // 添加选择事件
        tree.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (node == null) {
                    return;
                }
                Object object = node.getUserObject();
                if (node.isLeaf()) {
                    User user = (User) object;
                    System.out.println("你选择了：" + user.toString());
                }
            }
        });

        frame.setSize(600, 400);
        // 将窗口居中显示在屏幕上
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    @Data
    @AllArgsConstructor
    static class User implements Serializable {
        private static final long serialVersionUID = 862673456273991783L;

        private String name;

        @Override
        public String toString() {
            // 重点在toString，节点的显示文本就是toString
            return name;
        }
    }
}

